const mongoose = require('mongoose')
const {Head} = require('../untils/config')
const url = require('url')
mongoose.set('useCreateIndex', true) // 使设置的index生效

const schema = new mongoose.Schema({
  username: {type: String, required: true, index: {unique: true}},
  password: {type: String, required: true, },
  email: {type: String, required: true, index: {unique: true}},
  date: {type: Date, default: Date.now()},
  isAdmin: {type: Boolean, default: false},
  isFreeze: {type: Boolean, default: false},
  avatar: {type: String, default: url.resolve(Head.baseUrl, 'default.jpg')}
})

const UserModel = mongoose.model('User', schema)
UserModel.createIndexes() //使设置的index生效

let save = (data) => {
  let user = new UserModel(data)
  return user.save().then(()=> {
    return true
  }).catch(()=> {
    return false
  })
}

let login = (data) => {
  return UserModel.findOne(data)
}

let updatePassword = (email, password) => {
  return UserModel.updateOne({email}, {$set: {password}})
          .then(()=> {
            return true
          })
          .catch(()=> {
            return false
          })
}

let usersList = () => {
  return UserModel.find()
}

let updateFreeze = (email, isFreeze) => {
  return UserModel.updateOne({email}, {$set: {isFreeze}})
}

let deleteUser = (email) => {
  return UserModel.deleteOne({email})
}

let uploadAvatar = (username, avatar) => {
  return UserModel.updateOne({username}, {$set: {avatar}})
}

module.exports = {
  save,login,updatePassword,usersList,updateFreeze,deleteUser,uploadAvatar,
}